<?php
/**
 * @link https://www.kancloud.cn/cleverstone/ymb2
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

use builder\helper\App;
use builder\helper\Url;
use builder\export\ExportBuilder;
use yii\web\View;

/** @var View $this 视图实例 */
/** @var ExportBuilder $currentBuilder 组件实例 */
/** @var string $id 组件ID */
/** @var array $extraJs 额外的JS脚本 */
/** @var string $title 导出文件名 */
/** @var array $linker 下载链接 */
/** @var int $countLinker 下载链接数 */

$currentBuilder = $this->context;
$id = $currentBuilder->id;
$extraJs = $currentBuilder->extraJs;
$title = $currentBuilder->title;
$countLinker = count($linker);
?>
<script>
    -function (global, top) { "use strict";
        global.ym2App.controller("ym2.ctrl.<?= $id ?>", [
            "$scope",
            "$http",
            "$timeout",
            "ymSpinner",
            "layui",
            "ym2",
            "swal",
            "lodash",
            "$q",
            function ($scope, $http, $timeout, ymSpinner, layui, ym2, swal, lodash, $q) {
                var table = layui.table;
                var topSwal = top.swal;
                var topToastr = top.toastr;
                var topYmSpinner = top.ymSpinner;
                var HTTP_SUCCESS_CODE = <?= App::params('http.res.success') ?>;
                var HTTP_FAILURE_CODE = <?= App::params('http.res.failure') ?>;
                var HTTP_UNAUTHORITY_CODE = <?= App::params('http.res.unauthorized') ?>;
                var ADMIN_LOGIN_URL = '<?= Url::to(App::params('admin.route.login'), '') ?>';
                var dialog_dump_login_page = function (msg) {
                    ym2.swal.timer(
                        topSwal,
                        msg,
                        "自动跳转; <a href='"+ADMIN_LOGIN_URL+"' target='_top'>立即跳转<a/>",
                        function () {
                            top.open(ADMIN_LOGIN_URL, "_self");
                        },
                        3000
                    );
                };
                var linker = <?= !empty($linker) ? \yii\helpers\Json::encode($linker) : '[]' ?>;

                //初始化模型
                $scope.fileTitle = "<?= \yii\helpers\Html::encode($title) ?>";
                $scope.checkboxAll = 0;
                $scope.checkboxList = [];
                $scope.selectedList = [];
                $scope.selectedCount = 0;

<?php if ($countLinker > 0): ?>
                $scope.$watch("checkboxAll", function (newVal) {
                    for (let i = 0; i < <?= $countLinker ?>; i ++) {
                        $scope.checkboxList[i] = newVal;
                    }
                });
<?php endif; ?>
                $scope.$watch("checkboxList", function (newVal) {
                    let temp = [];
                    lodash.each(newVal, function (value, index) {
                        if (value === 1) {
                            temp.push(index);
                        }
                    });
                    $scope.selectedList = temp;
                    $scope.selectedCount = temp.length;
                }, true);

                // 批量下载
                $scope.batchDownload = function (fileFormat) {
                    if (linker.length <= 0) {
                        topToastr.warning("请选择");
                        return;
                    }

                    if ($scope.selectedList.length <= 0) {
                        topToastr.warning("请选择");
                        return;
                    }

                    let flag = topYmSpinner.show('下载中，请稍后...');
                    $scope.sequentialRequests(fileFormat).then(function () {
                        topYmSpinner.hide(flag);
                        topToastr.success('数据导出完成。');
                    }, function (error) {
                        topYmSpinner.hide(flag);
                        topToastr.error(error);
                        console.error(error);
                    });
                };
                $scope.sequentialRequests = function(fileFormat) {
                    let deferred = $q.defer();
                    let currentIndex = 0;

                    function nextRequest() {
                        if (currentIndex >= $scope.selectedList.length) {
                            deferred.resolve(1);
                            return;
                        }

                        let currentRow = $scope.selectedList[currentIndex];
                        let fileTitle = $scope.fileTitle + "_" + (currentRow + 1);
                        $http.get(linker[currentRow])
                            .then(function(result) {
                                let data = result.data;
                                if (data.data.columns.length <= 0) {
                                    deferred.reject(fileTitle + "：数据为空，已停止后续导出。");
                                } else {
                                    // 导出自定义数据
                                    table.exportFile(data.data.header, data.data.columns, {
                                        // 导出的文件格式，支持: csv,xls
                                        type: fileFormat,
                                        title: fileTitle,
                                    });
                                    currentIndex++;
                                    $timeout(function () {
                                        nextRequest(); // 递归调用
                                    }, 1000);
                                }
                            }, function (error) {
                                deferred.reject(fileTitle + "：" + (error.data || "系统错误，发起请求失败。"));
                            });
                    }

                    nextRequest(); // 启动请求链
                    return deferred.promise;
                };

                //下载请求
                $scope.downloadRequest = function (index, reqUrl, fileFormat) {
                    var flag = topYmSpinner.show('下载中，请稍后...');
                    $http.get(reqUrl).then(function (result) {
                        topYmSpinner.hide(flag);
                        var data = result.data;
                        switch (data.code) {
                            case HTTP_SUCCESS_CODE:
                                //200
                                if (data.data.columns.length <= 0) {
                                    topToastr.warning("数据为空。");
                                    return;
                                }

                                // 导出自定义数据
                                table.exportFile(data.data.header, data.data.columns, {
                                    // 导出的文件格式，支持: csv,xls
                                    type: fileFormat,
                                    title: $scope.fileTitle + "_" + (index + 1),
                                });

                                setTimeout(function () {
                                    topToastr.success('导出成功。');
                                }, 1000);
                                break;
                            case HTTP_FAILURE_CODE:
                                //500
                                topToastr.error(data.msg);
                                break;
                            case HTTP_UNAUTHORITY_CODE:
                                // 401
                                dialog_dump_login_page(data.msg);
                                break;
                            default:
                                topToastr.error(data.msg);
                        }
                    }, function (error) {
                        topYmSpinner.hide(flag);
                        topToastr.error(error.data || "系统错误，发起请求失败。");
                        global.console.error(error);
                    });
                };

                //额外的JS脚本
                <?= !empty($extraJs) ? implode("\n", $extraJs) : '' ?>

                //暴露页面数据更新回调，用于组件交互。
                global.ym2CbkExport["<?= $id ?>"] =  function () {
                    global.location.reload();
                };

            }]);
    }(window, top);
</script>
